<template>
  <div class="code-view-page">
    <!-- 大气的背景 -->
    <div class="grand-background">
      <div class="gradient-overlay"></div>
      <!-- <div class="subtle-pattern"></div> -->
    </div>

    <div class="ios-container">
      <div class="flex items-start">
        <div class="ios-navbar">
          <IOSBackButton @click="router.push('/code-share')" />
        </div>

        <div class="header-section ml-4">
          <h1 class="page-title">代码分享详情</h1>
          <p class="page-subtitle">查看并复制分享的代码片段</p>
        </div>
      </div>

      <div class="main-content">
        <div class="code-view-container" v-if="code">
          <!-- 代码信息栏 -->
          <div class="code-info-bar">
            <div class="info-left">
              <div class="language-tag">{{ language.toUpperCase() }}</div>
              <div class="code-stats">
                <span class="stat-item">
                  <span class="stat-icon">📄</span>
                  {{ code.split("\n").length }} 行
                </span>
                <span class="stat-item">
                  <span class="stat-icon">💾</span>
                  {{ (code.length / 1024).toFixed(1) }}KB
                </span>
              </div>
            </div>
            <div class="info-right">
              <button class="action-button secondary" @click="copyCode">
                <span class="button-icon">📋</span>
                复制代码
              </button>
              <button class="action-button primary" @click="shareAgain">
                <span class="button-icon">🔗</span>
                复制链接
              </button>
            </div>
          </div>

          <!-- 代码展示区域 -->
          <div class="code-display-section">
            <div class="code-header">
              <div class="file-tabs">
                <div class="file-tab active">
                  <span class="tab-icon">📝</span>
                  代码片段.{{ getFileExtension(language) }}
                </div>
              </div>
              <div class="code-actions">
                <button
                  class="icon-button"
                  @click="downloadCode"
                  title="下载代码"
                >
                  <span>💾</span>
                </button>
                <button
                  class="icon-button"
                  @click="toggleLineNumbers"
                  title="切换行号"
                >
                  <span>🔢</span>
                </button>
              </div>
            </div>

            <div
              class="code-display"
              :class="{ 'show-line-numbers': showLineNumbers }"
            >
              <div class="line-numbers" v-if="showLineNumbers">
                <div
                  v-for="(line, index) in codeLines"
                  :key="index"
                  class="line-number"
                >
                  {{ index + 1 }}
                </div>
              </div>
              <pre><code ref="codeEl" class="hljs" :class="language" v-html="highlightedCode" /></pre>
            </div>
          </div>

          <!-- 分享信息 -->
          <div class="share-info">
            <div class="share-details">
              <h3 class="share-title">分享信息</h3>
              <div class="share-meta">
                <div class="meta-item">
                  <span class="meta-label">分享ID:</span>
                  <span class="meta-value">{{ id }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">创建时间:</span>
                  <span class="meta-value">{{
                    new Date().toLocaleString("zh-CN")
                  }}</span>
                </div>
                <div class="meta-item">
                  <span class="meta-label">语言:</span>
                  <span class="meta-value">{{ language }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-else class="loading-container">
          <div class="loading-content">
            <div class="loading-spinner"></div>
            <p class="loading-text">正在加载代码...</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect, computed } from "vue";
import hljs from "highlight.js";
import "highlight.js/styles/github.css";
import IOSBackButton from "~/components/IOSBackButton.vue";

const route = useRoute();
const router = useRouter();
const id = route.params.id;

const code = ref("");
const language = ref("javascript");
const showLineNumbers = ref(true);

const codeEl = ref(null);

const codeLines = computed(() => {
  return code.value ? code.value.split("\n") : [];
});

onMounted(async () => {
  try {
    const { code: sharedCode, lan } = await $fetch(`/api/share-code/${id}`);
    code.value = sharedCode;
    if (lan) {
      language.value = lan;
    } else {
      // Try to detect language
      const detected = hljs.highlightAuto(sharedCode);
      if (detected.language) {
        language.value = detected.language;
      }
    }
  } catch (error) {
    alert("加载代码失败: " + error.message);
    router.push("/code-share");
  }
});

// Highlight code when code or language changes
watchEffect(() => {
  if (codeEl.value && code.value) {
    codeEl.value.innerHTML = code.value;
    hljs.highlightElement(codeEl.value);
  }
});

const highlightedCode = computed(() => {
  if (!code.value) return "";
  try {
    return hljs.highlight(code.value, {
      language: language.value,
    }).value;
  } catch {
    return code.value;
  }
});

function copyCode() {
  navigator.clipboard
    .writeText(code.value)
    .then(() => alert("代码已复制到剪贴板"))
    .catch(() => alert("复制失败"));
}

function shareAgain() {
  const shareUrl = window.location.href;
  navigator.clipboard
    .writeText(shareUrl)
    .then(() => alert("分享链接已复制到剪贴板"))
    .catch(() => alert("复制链接失败"));
}

function downloadCode() {
  const blob = new Blob([code.value], { type: "text/plain" });
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `code-snippet.${getFileExtension(language.value)}`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(url);
}

function toggleLineNumbers() {
  showLineNumbers.value = !showLineNumbers.value;
}

function getFileExtension(lang) {
  const extensions = {
    javascript: "js",
    typescript: "ts",
    python: "py",
    java: "java",
    cpp: "cpp",
    c: "c",
    html: "html",
    css: "css",
    php: "php",
    ruby: "rb",
    go: "go",
    swift: "swift",
    kotlin: "kt",
    rust: "rs",
    shell: "sh",
  };
  return extensions[lang] || "txt";
}
</script>

<style scoped>
.code-view-page {
  min-height: 100vh;
  position: relative;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.grand-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #667eea 0%, #b68be1 100%);
  z-index: -2;
}

.gradient-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    45deg,
    rgba(255, 255, 255, 0.1) 0%,
    rgba(255, 255, 255, 0.05) 50%,
    rgba(0, 0, 0, 0.05) 100%
  );
  z-index: -1;
}

.subtle-pattern {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: radial-gradient(
      circle at 25% 25%,
      rgba(255, 255, 255, 0.1) 0%,
      transparent 50%
    ),
    radial-gradient(
      circle at 75% 75%,
      rgba(255, 255, 255, 0.05) 0%,
      transparent 50%
    );
  background-size: 200px 200px;
  animation: patternMove 20s linear infinite;
}

@keyframes patternMove {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(100px, 100px);
  }
}

.ios-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 30px 40px;
  position: relative;
  z-index: 1;
}

.ios-navbar {
  padding: 20px 0;
  margin-bottom: 10px;
}

.header-section {
  text-align: center;
  margin-bottom: 50px;
}

.page-title {
  font-size: 2rem;
  font-weight: 800;
  color: white;
  margin-bottom: 16px;
  letter-spacing: -0.02em;
  text-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

.page-subtitle {
  font-size: 1rem;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
  font-weight: 400;
  letter-spacing: 0.5px;
}

.main-content {
  position: relative;
}

.code-view-container {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  padding: 50px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1), 0 8px 25px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.6);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.code-info-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 16px;
  border: 2px solid #e9ecef;
}

.info-left {
  display: flex;
  align-items: center;
  gap: 20px;
}

.language-tag {
  background: linear-gradient(135deg, #007aff 0%, #0051d5 100%);
  color: white;
  padding: 8px 16px;
  border-radius: 10px;
  font-size: 0.9rem;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.code-stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #6b7280;
  font-size: 0.95rem;
  font-weight: 500;
}

.stat-icon {
  font-size: 1rem;
}

.info-right {
  display: flex;
  gap: 12px;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  border-radius: 10px;
  border: none;
  font-size: 0.95rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.action-button.primary {
  background: linear-gradient(135deg, #007aff 0%, #0051d5 100%);
  color: white;
  box-shadow: 0 4px 15px rgba(0, 122, 255, 0.3);
}

.action-button.primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 122, 255, 0.4);
}

.action-button.secondary {
  background: white;
  color: #1d1d1f;
  border: 2px solid #e5e5ea;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.action-button.secondary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.12);
}

.code-display-section {
  margin-bottom: 30px;
}

.code-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f1f3f4;
  border: 2px solid #e5e5ea;
  border-bottom: none;
  border-radius: 12px 12px 0 0;
  padding: 16px 20px;
}

.file-tabs {
  display: flex;
}

.file-tab {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: white;
  border-radius: 8px;
  font-size: 0.9rem;
  font-weight: 500;
  color: #374151;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
}

.tab-icon {
  font-size: 1rem;
}

.code-actions {
  display: flex;
  gap: 8px;
}

.icon-button {
  width: 36px;
  height: 36px;
  border: none;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
}

.icon-button:hover {
  background: #f9f9f9;
  transform: translateY(-1px);
}

.code-display {
  background: #f8f9fa;
  border: 2px solid #e5e5ea;
  border-top: none;
  border-radius: 0 0 12px 12px;
  overflow: hidden;
  position: relative;
  display: flex;
}

.line-numbers {
  background: #f1f3f4;
  padding: 30px 16px;
  border-right: 1px solid #e1e4e8;
  user-select: none;
  font-family: "SF Mono", Monaco, "Cascadia Code", "Roboto Mono", Consolas,
    "Courier New", monospace;
  font-size: 0.85rem;
  line-height: 1.6;
  color: #6b7280;
  min-width: 60px;
}

.line-number {
  text-align: right;
  padding-right: 8px;
}

.code-display pre {
  margin: 0;
  padding: 30px;
  overflow-x: auto;
  font-family: "SF Mono", Monaco, "Cascadia Code", "Roboto Mono", Consolas,
    "Courier New", monospace;
  font-size: 0.95rem;
  line-height: 1.6;
  flex: 1;
}

.code-display.show-line-numbers pre {
  padding-left: 20px;
}

.code-display code {
  background: none !important;
  padding: 0 !important;
}

.share-info {
  background: #f8f9fa;
  border-radius: 16px;
  padding: 30px;
  border: 2px solid #e9ecef;
}

.share-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1d1d1f;
  margin-bottom: 20px;
}

.share-meta {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.meta-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.meta-label {
  font-size: 0.85rem;
  color: #6b7280;
  font-weight: 500;
}

.meta-value {
  font-size: 0.95rem;
  color: #1d1d1f;
  font-weight: 600;
  font-family: "SF Mono", Monaco, "Cascadia Code", "Roboto Mono", Consolas,
    monospace;
}

.loading-container {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 24px;
  padding: 80px 50px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1), 0 8px 25px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.6);
  border: 1px solid rgba(255, 255, 255, 0.2);
  text-align: center;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e5e5ea;
  border-top: 4px solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 1.1rem;
  color: #6b7280;
  margin: 0;
}

.button-icon {
  font-size: 1.1rem;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .ios-container {
    max-width: 1000px;
    padding: 30px;
  }

  .code-view-container {
    padding: 40px;
  }
}

@media (max-width: 768px) {
  .ios-container {
    padding: 20px;
  }

  .code-view-container {
    padding: 30px;
  }

  .page-title {
    font-size: 2.5rem;
  }

  .code-info-bar {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
  }

  .info-left {
    justify-content: center;
  }

  .info-right {
    justify-content: center;
  }

  .share-meta {
    grid-template-columns: 1fr;
  }

  .code-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .code-actions {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .code-view-container {
    padding: 24px;
  }

  .page-title {
    font-size: 2rem;
  }

  .page-subtitle {
    font-size: 1.1rem;
  }

  .info-right {
    flex-direction: column;
  }
}
</style>
